package com.xxl.job.executor.service.jobhandler;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonArray;
import com.mysql.cj.util.StringUtils;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.DateUtil;
import com.xxl.job.executor.mvc.mapper.VisitorApplyMapper;
import com.xxl.job.executor.mvc.mapper.VisitorApplyPlanDataMapper;
import com.xxl.job.executor.mvc.mapper.VisitorApplyPlanMapper;
import com.xxl.job.executor.mvc.pojo.VisitorApply;
import com.xxl.job.executor.mvc.pojo.VisitorApplyPlan;
import com.xxl.job.executor.mvc.pojo.VisitorApplyPlanData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
@Slf4j
public class VisitorJob {

    @Autowired
    VisitorApplyPlanMapper visitorApplyPlanMapper;

    @Autowired
    VisitorApplyMapper visitorApplyMapper;

    @Autowired
    VisitorApplyPlanDataMapper visitorApplyPlanDataMapper;

    @Autowired
    RestTemplate restTemplate;

    /**
     * 执行修改任务状态
     */
    @XxlJob("visitorApplyJobHandler")
    public ReturnT<String> visitorApplyJobHandler(String param) throws Exception {

        log.info("VisitorJob->visitorApplyJobHandler.");
        log.info("VisitorJob->visitorApplyJobHandler开始");

        Date now = new Date();
        VisitorApplyPlan visitorApplyPlan = new VisitorApplyPlan();
        visitorApplyPlan.setStatusCode("01");
        visitorApplyPlan.setEndBookDate(DateUtil.parseDate(DateUtil.formatDate(now)));
        /**
         * 查询计划表中 状态为初始化的
         */
        List<VisitorApplyPlan> planList = visitorApplyPlanMapper.findList(visitorApplyPlan);
        log.info("VisitorJob->visitorApplyJobHandler>>>{}", planList);
        long dateNow = DateUtil.parse(DateUtil.format(now, "yyyy-MM-dd"), "yyyy-MM-dd").getTime();
        long time = DateUtil.parse(DateUtil.format(now, "HH:mm:ss"), "HH:mm:ss").getTime();
        for (VisitorApplyPlan plan : planList) {
            long bookDate = plan.getBookDate().getTime();
            long delayTime = plan.getDelayTime().getTime();
            long endTime = plan.getEndTime().getTime();
            VisitorApply visitorApply = new VisitorApply();
            /*
            visitorApply.setBeginDateStr(DateUtil.formatDate(plan.getBookDate()));
            visitorApply.setBeginTimeStr(DateUtil.format(plan.getBeginTime(),"HH:mm:ss"));
            visitorApply.setEndDateStr(DateUtil.formatDate(plan.getBookDate()));
            visitorApply.setEndTimeStr(DateUtil.format(plan.getEndTime(),"HH:mm:ss"));
            */
            visitorApply.setPlanId(new Long(plan.getPlanId()));
            /**
             * 查询执行计划对应的apply
             */
            List<VisitorApply> visitorApplyList = visitorApplyMapper.findList(visitorApply);
            // 过滤掉03的
            visitorApplyList = visitorApplyList.stream().filter(it->!"03".equals(it.getStatusCode()))
                    .collect(Collectors.toList());
            ObjectMapper mapper = new ObjectMapper();
            for (VisitorApply visitorApply1 : visitorApplyList) {
                String statusCode = "";
                String logStr = "";
                /**
                 * 已出
                 */
                if ("03".equals(visitorApply1.getTransitStatus())) {
                    statusCode = "05";
                    logStr = "visitorApplyJobHandler修改为已完成";
                } else if ("01".equals(visitorApply1.getTransitStatus()) ||
                        "02".equals(visitorApply1.getTransitStatus())) {
                    /**
                     * 01,未通行；02，已进；
                     */
                    if (dateNow == bookDate && time < endTime) {
                        // 未到结束时间
                        logStr = "visitorApplyJobHandler修改为执行中";
                        if ("01".equals(visitorApply1.getTransitStatus()) && "02".equals(visitorApply1.getStatusCode())) {
                            /**
                             * 下发名单
                             */
                            String url = "https://pmp.tzysoft.com/scenicspot/createNameList";

                            JSONObject postData = new JSONObject();
                            postData.put("relationId", visitorApply1.getRelationId());
                            log.info("visitorApplyJobHandler任务下发名单入参{}", JSONObject.toJSONString(postData));

                            JSONObject respJson = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();

                            log.info("visitorApplyJobHandler任务下发名单出参{}", JSONObject.toJSONString(respJson));
                            if ("000000000".equals(respJson.getString("code"))) {
                                statusCode = "01";
                                log.info("visitorApplyJobHandler任务下发名单成功{}", JSONObject.toJSONString(respJson));
                            } else {
                                statusCode = null;
                                log.info("visitorApplyJobHandler任务下发名单异常{}", JSONObject.toJSONString(respJson));
                            }
                        } else {
                            statusCode = "01";
                        }
                    } else {
                        // 超过结束时间
                        if ("01".equals(visitorApply1.getTransitStatus())) {
                            // 未通行
                            statusCode = "06";
                            logStr = "visitorApplyJobHandler修改为已过期";
                        } else {
                            // 已进
                            if (dateNow == bookDate && time < delayTime) {
                                statusCode = "04";
                                logStr = "visitorApplyJobHandler修改为已滞留";
                            } else {
                                statusCode = "07";
                                logStr = "visitorApplyJobHandler修改为已清场";
                            }
                        }
                    }
                } else {
                    log.info("visitorApplyJobHandler>>通行状态异常");
                    continue;
                }
                log.info(logStr + "statusCode:{},planUpdate:{},transitStatus{}", statusCode, (time > delayTime), visitorApply1.getTransitStatus());
                if (!StringUtils.isNullOrEmpty(statusCode) && !statusCode.equals(visitorApply1.getStatusCode())) {
                    VisitorApply vaUpdate = new VisitorApply();
                    vaUpdate.setRelationId(visitorApply1.getRelationId());
                    vaUpdate.setStatusCode(statusCode);
                    vaUpdate.setUpdateTime(now);
                    visitorApplyMapper.updateByRelationId(vaUpdate);
                    log.info(logStr + ",入参：{}", mapper.writeValueAsString(vaUpdate));
                }
            }
            int unFinishCount = visitorApplyMapper.selectUnFinishCount(plan.getPlanId());
            // 更新执行计划状态
            if ((dateNow > bookDate || (dateNow == bookDate && time > delayTime)) && unFinishCount == 0) {
                VisitorApplyPlan vapUpdate = new VisitorApplyPlan();
                vapUpdate.setPlanId(plan.getPlanId());
                vapUpdate.setStatusCode("02");
                visitorApplyPlanMapper.update(vapUpdate);
            }
        }
        log.info("VisitorJob->visitorApplyJobHandler结束");
        return ReturnT.SUCCESS;
    }

    @XxlJob("visitorCountJobHandler")
    public ReturnT<String> visitorCountJobHandler(String param) {
        log.info("VisitorJob->visitorCountJobHandler开始");
        // VisitorApplyPlan visitorApplyPlan = new VisitorApplyPlan();
        // visitorApplyPlan.setStatusCode("01");
        /**
         * 查询计划表中 状态为初始化的
         */
        List<VisitorApplyPlan> planList = visitorApplyPlanMapper.findListForCalc();
        for (VisitorApplyPlan plan : planList) {
            VisitorApply visitorApply = new VisitorApply();
            visitorApply.setPlanId(new Long(plan.getPlanId()));
            /**
             * 查询执行计划对应的apply的统计数据
             */
            VisitorApplyPlanData visitorApplyData = visitorApplyPlanDataMapper.getVisitorCount(visitorApply);
            if(Objects.isNull(visitorApplyData)) {
                continue;
            }
            /**
             * 查询计划表是否有数据
             */
            VisitorApplyPlanData vapdQuery = new VisitorApplyPlanData();
            vapdQuery.setPlanId(plan.getPlanId());
            List<VisitorApplyPlanData> vppd = visitorApplyPlanDataMapper.findList(vapdQuery);
            Date now = new Date();
            if (vppd != null && vppd.size() > 0) {
                // 更新数据
                visitorApplyData.setPlanId(plan.getPlanId());
                visitorApplyData.setExcuteTime(now);
                visitorApplyPlanDataMapper.update(visitorApplyData);
            } else {
                // 保存数据
                visitorApplyData.setPlanId(plan.getPlanId());
                visitorApplyData.setProjectId(plan.getProjectId());
                visitorApplyData.setPlanDate(plan.getBookDate());
                visitorApplyData.setCreateTime(now);
                visitorApplyPlanDataMapper.insert(visitorApplyData);
            }
            // 更新执行计划状态
            if ("02".equals(plan.getStatusCode())) {
                VisitorApplyPlan vapUpdate = new VisitorApplyPlan();
                vapUpdate.setPlanId(plan.getPlanId());
                vapUpdate.setStatusCode("03");
                visitorApplyPlanMapper.update(vapUpdate);
            }
        }
        log.info("VisitorJob->visitorCountJobHandler结束");
        return ReturnT.SUCCESS;
    }
}
